<template>
  <div class="app-container">
    <el-row :gutter="15" class="mb8">
      <el-col :span="1.5">
        <el-button plain size="mini" icon="el-icon-download" @click="handleExport">导出
        </el-button>
      </el-col>
      <el-form :model="formData" @submit.prevent :inline="true" class="el-form-search">
        <!--设备选择-->
        <el-form-item label="设备" porp="device" class="el-form-search-item">
          <el-select v-model="formData.device" placeholder="请选择设备类型" clearable filterable @change="setChannelList">
            <el-option v-for="device in deviceList" :key="device.zhGuid" :label="device.devName"
              :value="device.zhGuid" />
          </el-select>
        </el-form-item>
        <!--通道选择-->
        <el-form-item label="通道" porp="channel" class="el-form-search-item">
          <el-select v-model="formData.channel" placeholder="请选择设备类型" clearable filterable>
            <el-option v-for="channel in channelList" :key="channel.tdGuid" :label="channel.channelName"
              :value="channel.tdGuid" />
          </el-select>
        </el-form-item>
        <!--数据类型-->
        <el-form-item label="数据类型" porp="selectedTable" class="el-form-search-item">
          <el-select v-model="formData.selectedTable" placeholder="请选择数据类型">
            <el-option v-for="table in tables" :key="table.value" :label="table.label" :value="table.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="时间" porp="timeRange" class="el-form-search-item">
          <!-- 时间选择 -->
          <el-date-picker :clearable="false" v-model="formData.timeRange" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
            start-placeholder="开始时间" end-placeholder="结束时间" style="width: 340px" value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss" />
        </el-form-item>
        <!-- 查询按钮 -->
        <el-button type="primary" size="mini" icon="el-icon-search" @click="getList">搜索
        </el-button>
      </el-form>
    </el-row>

    <!-- 数据表格 -->
    <el-table border ref="elTable" :data="tableData" height="calc(100vh - 200px)" @row-dblclick="handleRowDbClick"
      highlight-current-row>
      <!--      <el-table-column prop="tdGuid" label="通道"></el-table-column>-->
      <el-table-column prop="timedate" label="时间" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.timedate) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-for="(item, index) in fieldsList" :key="item.id" :prop="item.fieldName"
        :label="item.fieldCnName + handelIndex(index)">
      </el-table-column>
      <!--      <el-table-column  fixed="right" label="操作" width="100">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button @click="handleClick(scope.row)" type="text" size="small"-->
      <!--          >查看-->
      <!--          </el-button-->
      <!--          >-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <!-- 分页控件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="formData.pageNum" :limit.sync="formData.pageSize"
      @pagination="getList" />
    <!-- 对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" title="详细数据" :visible.sync="dialogVisible" width="80%"
      :before-close="handleClose">
      <!-- 在对话框中使用DataTable组件 -->
      <data-detail :params="queryParams" ref="dialogDataTable"></data-detail>

      <!--      <span slot="footer" class="dialog-footer">-->
      <!--        <el-button @click="dialogVisible = false">关闭</el-button>-->
      <!--        <el-button type="primary" @click="handleConfirm">确定</el-button>-->
      <!--      </span>-->
    </el-dialog>
  </div>
</template>

<script>
import { getIhr, getUhr } from '@/api/data_analysis/baseData.js'
import { getDeviceListFold } from '@/api/device/device'
import { getToken } from "@/utils/auth";
import { getIhrData } from '@/api/system/settingQUeryFields'
import { getTableDefinition } from '@/api/system/settingQUeryFields'
import DataDetail from '../components/DataDetail'

import * as XLSX from 'xlsx'
import FileSaver from 'file-saver'

export default {
  components: {
    DataDetail
  },
  data() {
    return {
      total: 0,
      tableHeight: window.innerHeight - 180,
      tables: [
        { value: 'base', label: '原始数据' },
        { value: 'avg', label: '平均值' },
        { value: 'max', label: '最大值' },
        { value: 'min', label: '最小值' }
      ],
      formData: {
        pageNum: 1,
        pageSize: 30,
        selectedTable: 'base',
        timeRange: [
          this.parseTime(new Date(2025, 0, 20)), // 月份从0开始（0=1月）
          this.parseTime(new Date(2025, 0, 22))
        ],
        device: '',
        channel: '',
        tableInfo: "db_uhra",

      },

      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          }, {
            text: "最近一天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },

      tableData: [],
      deviceList: [],
      channelList: [],
      fieldsList: [],
      tableInfoList: [],


      dialogVisible: false,
      queryParams: {
        // 查询参数

      }
    }
  },
  watch: {
    formData: {
      handler(newForm, oldForm) {
        let obj = Object.assign({}, newForm);
        obj.datetime = newForm.timeRange;
        obj.device = newForm.device;
        obj.channel = newForm.channel;
        this.$store.commit('UPDATE_FILTER_CONDITIONS', obj)
        console.log(this.$store.state.filterConditions.filterConditions)
      }, deep: true
    }

  },
  created() {

    let obj = this.$store.state.filterConditions.filterConditions;
    if (obj) {
      if (obj.datetime) this.formData.timeRange = obj.datetime
      this.formData.device = obj.device;
      this.formData.channel = obj.channel;
    }
    this.getFieldsAndTableList()
    this.getDeviceList()
    // this.loadData()

  },
  methods: {
    getFieldsAndTableList(e) {

      this.getConfigKey("sys:fenxi:limit").then((response) => {
        getIhrData({
          isShow: 1,
          limit: response.msg,
          tablePrefixList: ['db_uhra', 'db_uhrb', 'db_uhrc']
        }).then(response => {
          this.fieldsList = response.data;
          // this.fieldsList.push('tdGuid')
          console.log(this.fieldsList);

          this.getList()

        })
      });


      getTableDefinition().then(response => {
        this.tableInfoList = response.rows;
        console.log(this.tableInfoList);
      })
    },
    getList() {

      let dateTime = {
        startTime: '',
        endTime: ''
      }
      console.log(this.formData.timeRange && this.formData.timeRange.length > 1)
      if (this.formData.timeRange && this.formData.timeRange.length > 1) {
        dateTime.startTime = this.parseTime(this.formData.timeRange[0])
        dateTime.endTime = this.parseTime(this.formData.timeRange[1])
      }
      console.log(dateTime)
      // 格式化日期为后端期望的格式
      getUhr({
        pageNum: this.formData.pageNum,
        pageSize: this.formData.pageSize,
        tdGuid: this.formData.channel,
        tableName: "db_uhra" + (this.formData.selectedTable === 'base' ? "" : this.formData.selectedTable),
        fields: this.fieldsList.map((item) => item.fieldName),
        ...dateTime
      })
        .then((res) => {
          console.log("输出数据")
          console.log(res)
          this.tableData = res.rows;
          this.total = res.total
          this.$refs.elTable.doLayout()
        })
        .catch((err) => {
          this.$message.error('数据加载失败')
        })
    },
    loadData() {
      // if (
      //   !this.formData.selectedTable ||
      //   !this.formData.timeRange?.length === 2
      // ) {
      //   this.$message.warning('请选择表和时间范围')
      //   return
      // }

      this.getList()
    },

    handleClick(row) {
      console.log(row)
      let suffix
      if (this.formData.selectedTable !== 'db_basedata') {
        suffix = this.formData.selectedTable.slice(-3)
      }
      //跳转到详细页面
      this.$router.push({
        path: '/data/data-detail',
        name: 'dataDetail',
        params: {
          timedate: row.timedate,
          tableNameSuffix: this.formData.selectedTable === 'base' ? "" : this.formData.selectedTable,
          tdGuid: row.tdGuid
        }
      })
    },

    getDeviceList() {
      getDeviceListFold().then((res) => {
        console.log(res)
        this.deviceList = res.rows

        if (this.formData.device !== null || this.formData.device !== "") {
          this.channelList = this.deviceList.filter((item) => {
            return item.zhGuid === this.formData.device
          })[0].channelList
        }
      })
    },
    setChannelList(selectedValue) {
      console.log(selectedValue)
      console.log(this.deviceList)

      this.channelList = this.deviceList.filter((item) => {
        return item.zhGuid === selectedValue
      })[0].channelList
      this.formData.channel = this.channelList[0].tdGuid
    },
    // handelTableInfoChang(e){
    //
    //   this.getFieldsAndTableList(e)
    // }
    handelIndex(num) {
      if (num % 3 === 0) {
        return "(A相)"
      } else if (num % 3 === 1) {
        return "(B相)"
      } else if (num % 3 === 2) {
        return "(C相)"
      }
    },
    handleRowDbClick(row, column, event) {
      console.log(row.tdGuid)
      this.queryParams = {
        timedate: row.timedate,
        tableNameSuffix: this.formData.selectedTable === 'base' ? "" : this.formData.selectedTable,
        tdGuid: row.tdGuid
      }
      this.openDialog()
    },

    // 打开对话框
    openDialog() {
      this.dialogVisible = true;
      // 如果需要在打开对话框时重新加载数据，可以添加以下代码
      this.$nextTick(() => {
        this.$refs.dialogDataTable.getList();
      });
    },

    // 对话框关闭前的回调
    handleClose(done) {
      // 可以在这里添加关闭前的确认逻辑
      done();
    },

    // 确认按钮点击事件
    handleConfirm() {
      // 可以获取子组件的数据进行处理
      const tableData = this.$refs.dialogDataTable.tableData;
      console.log('表格数据:', tableData);

      // 关闭对话框
      this.dialogVisible = false;
    },

    // 更新查询参数
    updateQueryParams(newParams) {
      this.queryParams = { ...this.queryParams, ...newParams };
      // 如果对话框已打开，刷新数据
      if (this.dialogVisible && this.$refs.dialogDataTable) {
        this.$refs.dialogDataTable.getList();
      }
    },
    handleExport() {
      // 格式化日期为后端期望的格式
      const formatDate = (date) => {
        const d = new Date(date)
        const pad = (num) => (num < 10 ? '0' + num : num)

        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
      }

      getUhr({
        tdGuid: this.formData.channel,
        tableName: "db_uhra" + (this.formData.selectedTable === 'base' ? "" : this.formData.selectedTable),
        fields: this.fieldsList.map((item) => item.fieldName),
        startTime: formatDate(this.formData.timeRange[0]),
        endTime: formatDate(this.formData.timeRange[1])
      })
        .then((res) => {
          this.ExportExcel(res.rows)
        })
    },
    ExportExcel(ExportData) {
      const workbook = XLSX.utils.book_new()
      let arr3 = this.fieldsList.map((item) => {
        return item.fieldCnName
      })
      let arr4 = this.fieldsList.map((item) => {
        return item.fieldName
      })
      // 创建工作簿
      const headers = ['时间', ...arr3]
      const fields = ['timedate', ...arr4]
      // 定义自定义表头
      // const headers = ['日期', '姓名', '地址']; // 自定义表头
      // 定义表头对应的字段名
      // const fields = ['date', 'name', 'address'];
      // console.log(headers)
      // console.log(fields)

      // return

      // 准备数据（包括表头）
      const data = [headers]

      // 添加数据行
      ExportData.forEach(item => {
        const row = []
        fields.forEach(field => {
          row.push(item[field])
        })
        data.push(row)
      })
      console.log(data)

      // 将数据转换为工作表
      const worksheet = XLSX.utils.aoa_to_sheet(data)

      // 设置列宽
      const colWidth = [
        { wch: 15 } // 日期列宽
      ]
      for (let i = 0; i++; i < this.fieldsList.length + 1) {
        colWidth.push({ wch: 10 })
      }

      worksheet['!cols'] = colWidth

      // 添加工作表到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '表格数据')

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array', cellStyles: true })
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      FileSaver.saveAs(blob, '表格数据.xlsx')
    }

  }
}
</script>
